package com.FengChaoSystem.servlet;

import com.FengChaoSystem.pojo.Imag;
import com.FengChaoSystem.pojo.User;
import com.FengChaoSystem.service.UserImpl;
import com.FengChaoSystem.service.UserService.UserService;
import com.FengChaoSystem.untils.FileUploadUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addImgServlet")
public class AddImgServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        //通过工具类获取成员的信息
        String file = getServletContext().getRealPath("/head_img/");
        System.out.println(file);
        Map<String,String> map = new FileUploadUtil().File_upload(request,file+"\\");



        //创建img对象用来封装数据
        Imag img=new Imag();
        try {
            BeanUtils.populate(img,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("servlet获取的img数据为:"+img);
        System.out.println(img.toString());
        //创建service对象将头像数据存入到表中

        HttpSession session = request.getSession();
        String userName = (String)session.getAttribute("userName");

        User temp=new User();
        temp.setUserName(userName);
        temp.setImagPath("http://localhost:80/head_img/"+img.getNewFileName());
        System.out.println(img.getFileName());
        System.out.println(img.getNewFileName());
        UserImpl userDao  = new UserService();
        System.out.println("注册名为"+temp.getUserName());
        System.out.println("保存的路经为"+temp.getImagPath());
        session.removeAttribute("userName");
        userDao.addImg(temp);
        request.getRequestDispatcher("/login.html").forward(request,response);
    }
}
